import React from 'react'
import { connect } from 'dva'
import { Menu, Dropdown } from 'antd'
import styles from '../index.less'

@connect(({warehouse}) => ({
  list: warehouse.list
}))
export default class WareHouseSelect extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      current: {},
    }
  }

  componentDidMount() {
    this.fetchData()
  }

  fetchData = () => {
    const {dispatch} = this.props
    dispatch({
      type: 'warehouse/list',
    })
  }

  onMenuClick = ({key}) => {
    const {list = []} = this.props
    this.setState({
      current: list.find(item => Number(item.id) === Number(key)) || {},
    })
  }

  renderMenu = () => {
    const {list = []} = this.props
    return (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
        {list.map(item => (
          <Menu.Item key={item.id}>{item.name}</Menu.Item>
        ))}
      </Menu>
    )
  }

  getSelect = () => {
    const {current} = this.state
    const {list} = this.props
    if (current.name) return current.name
    return list.length > 0 ? list[0].name : ''
  }

  render() {
    const name = this.getSelect()
    return name ?
      <Dropdown overlay={this.renderMenu()}>
        <span style={{marginRight: 10}} className='pointer'>{name}</span>
      </Dropdown> :
      ''
  }
}
